package org.nudt.system.service

import org.nudt.common.exception.BadRequestException
import org.nudt.common.utils.FileUtil
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Value
import org.springframework.scheduling.annotation.Async
import org.springframework.stereotype.Service
import org.springframework.web.multipart.MultipartFile
import java.io.BufferedReader
import java.io.File
import java.io.IOException
import java.io.InputStreamReader
import java.nio.charset.Charset

@Service
class FileService(
    @Value("\${file.pic-path}") private val picPath: String,
) {
    
    private val logger = LoggerFactory.getLogger(FileService::class.java)
    
    fun upload(file: MultipartFile): String {
        // 检查文件大小
        FileUtil.checkSize(10, file.size)
        // 上传文件
        val file = FileUtil.upload(file, picPath)
        // 检查文件是否上传成功
        if (file == null) {
            throw BadRequestException("上传文件出错")
        } else {
            // 更新用户头像
            val img = "http://192.168.0.177/upload/video/${file.name}"
            return img
        }
        
    }
    
    @Async
    fun ffmpegVideo(destFile: File, audio: File, video: File, dir: File) {
        try {
            val processBuilder = ProcessBuilder("ffmpeg", "-i", audio.absolutePath, "-i", video.absolutePath, "-c", "copy", destFile.absolutePath)
            processBuilder.redirectErrorStream(true)
            val process = processBuilder.start()
            logger.info(process.inputReader(Charset.forName("UTF-8")).readText())
            dir.delete()
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }
}